/**
 * Created By zhangQ 2018/4/29
 * [获得EJS模板]
 */
import axiosUtils from '@/api/env'
import Vue from 'vue'
import uuid from 'uuid'
import moment from 'moment'
import { camelCaseName } from '@/components/common/utils'

const customAxios = axiosUtils._initAxios()

let templatePrefix = 'static/template/'
let templateBaseUrl = process.env.NODE_ENV !== 'production' ? ('http://localhost:9080/' + templatePrefix) : templatePrefix
let generationRef = 'generationVue'

let vueUtil = {
  firstUpperCase (str) {
    let resStr = str[0].toUpperCase() + str.substr(1, str.length - 1)
    return resStr
  },
  /**
   * TODO(下划线转为驼峰格式)
   * @param str:::字符串
   * @param firstUppercase:::首字母是否大写，默认小写
   * @auther zhangQ
   * @date 2018/5/1 21:48
   */
  camelCaseName (str, firstUppercase = false) {
    return camelCaseName(str, firstUppercase)
  },
  formatTime (val, gs = 'YYYY-MM-DD HH:mm:ss') {
    if (val) {
      return moment(val).format(gs)
    }
    return moment().format(gs)
  }
}

let templateUtil = {
  initTemplate (templateName, datas) {
    if (!datas) {
      return
    }
    return new Promise((resolve, reject) => {
      this.getTemplateForAjax(templateName)
        .then(({ templateConf, templateStr }) => {
          let id = 'generationVue' + uuid.v4()
          $('<div id="' + id + '" style="display:none"></div>').appendTo(document.body)
          return this.initVue(id, templateStr, datas)
        })
        .then((vue) => {
          vue.$nextTick(function () {
            let templateContent = vue.$refs[generationRef].innerHTML
            // 处理特殊字符
            templateContent = templateContent.replace(/and#/g, '&&').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
            resolve(templateContent)
          })
        })
    })
  },
  /**
   * ajax获得模板路径
   * @auther zhangQ
   * @date 2018/4/20 18:40
   */
  getTemplateForAjax (templateName) {
    return new Promise((resolve, reject) => {
      customAxios({
        url: templateBaseUrl + templateName + '.html?time=' + Date.now(),
        method: 'get'
      }).then((res) => {
        if (!res.data) {
          reject(new Error('未找到模板'))
        } else if (res.data) {
          console.log('模板路径：', templatePrefix + templateName + '.html')
          let templateConf = {}
          let templateStr = res.data
          let templateStrArray = JSON.stringify(templateStr).split('\\r\\n')
          let index = 0
          templateStrArray.forEach((item) => {
            if (!(item.indexOf('<template') >= 0 || item.indexOf('</template') >= 0)) {
              templateStrArray[index] = item.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/&&/g, 'and#')
            }
            index++
          })
          templateStr = JSON.parse(templateStrArray.join('\\r\\n'))
          // console.log('templateStr', templateStr)
          // for (let i = 0; i < templateHtml.length; i++) {
          //   if (templateHtml[i].nodeName.toLocaleLowerCase() === 'config') {
          //     templateConf = JSON.parse(templateHtml[i].innerHTML.replace(/^\s+|\s+|\r+|\n+$/g, ''))
          //   }
          //   if (templateHtml[i].nodeName.toLocaleLowerCase() === 'content') {
          //     // printHtml = templateHtml[i].innerHTML.replace(/^\s+|\s+$/g, '')
          //     templateStr = templateHtml[i].innerHTML
          //   }
          // }
          resolve({ templateConf, templateStr })
        }
      }).catch((err) => {
        reject(err)
      })
    })
  },
  initVue (id, template, datas) {
    return new Promise((resolve, reject) => {
      if (typeof datas !== 'object') {
        reject(new Error('数据源必须是对象'))
      }
      let vue = new Vue({
        template: '<div ref="' + generationRef + '" style="display:none" >' + template + '</div>',
        el: '#' + id,
        data: datas,
        methods: vueUtil,
        created () {
        }
      })
      resolve(vue)
    })
  }
}

export default templateUtil
